const app = new Vue({
    el: '#app',
    data() {
        //校验学号唯一性,自定义校验规则，格式是固定的。
        const rulesSNo = (rule, value, callback) => {
            if (this.isEdit) {
                callback();
            }
            //使用axios访问接口，进行rules
            axios
                .post(
                    this.baseUrl + 'sno/check/',
                    {
                        sno: value,
                    },
                    {
                        headers: {
                            'Authorization': 'Token ' + sessionStorage.getItem('token')
                        }
                    }
                )
                .then((res) => {
                    if (res.data.code === 1) {
                        //请求成功
                        if (res.data.exists) {
                            callback(new Error("学号已经存在！"));
                        } else {
                            callback();
                        }
                    } else {
                        callback(new Error("校验学号后端出现异常！"));
                    }
                })
                .catch((err) => {
                    console.log(err);
                })
        }

        return {
            students: [], //所有的学生信息
            pageStudents: [], //每页后当前页的学生
            baseUrl: "http://shot.com/",
            inputStr: '',  //输入的查询条件
            selectStudents: [], //选择复选框，把选择记录放到的集合

            total: 0, //数据的总行数
            currentpage: 1,//当前的所在的页
            pagesize: 10, //每页显示多少页
            dialogVisible: false, //弹出框是否展示
            dialogTitle: "", //弹出框的标题
            isView: false,   //标识是否是查看
            isEdit: false,   //标识是否是编辑
            // 学生信息
            studentForm: {
                sno: '',
                name: '',
                gender: '',
                birthday: '',
                mobile: '',
                email: '',
                address: '',
                image: '',
                imageUrl: '',
            },
            rules: {
                sno: [
                    { required: true, message: "学号不能为空", trigger: "blur" },
                    { pattern: /^[9][5]\d{3}$/, message: "学号必须是95开头的五位数", trigger: "blur" },
                    { validator: rulesSNo, trigger: "blur" } //校验学号是否存在
                ],
                name: [
                    { required: true, message: "姓名不能为空", trigger: "blur" },
                    { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: "姓名必须是2到5个汉字", trigger: "blur" }
                ],
                gender: [
                    { required: true, message: "性别不能为空", trigger: "change" }
                ],
                birthday: [
                    { required: true, message: "生日不能为空", trigger: "change" }
                ],
                mobile: [
                    { required: true, message: "手机号码不能为空", trigger: "blur" },
                    { pattern: /^[1][3894]\d{9}$/, message: "手机号码必须符合规范", trigger: "blur" }
                ],
                email: [
                    { required: true, message: "邮箱地址不能为空", trigger: "blur" },
                    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w)*\.\w+([-.]\w+)*$/, message: "邮箱地址必须符合规范", trigger: "blur" }
                ],
                address: [
                    { required: true, message: "家庭住址不能为空", trigger: "blur" }
                ]
            }
        }

    },
    mounted() {
        //自动加载数据
        this.getStudents();
    },
    methods: {
        //获取所有学生信息  -- function 关键字可写可不写
        getStudents: function () {
            //使用Axios实现Ajax请求
            let that = this;
            axios
                .get(
                    this.baseUrl + "students/",
                    {
                        headers: {
                            'Authorization': 'Token ' + sessionStorage.getItem('token')
                        }
                    }
                )
                .then(function (res) {
                    //请求成功后执行的函数
                    console.log(res.code)
                    if (res.data.code === 1) {
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '加载数据成功',
                            type: 'success'
                        })
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(function (err) {
                    //请求失败之后执行的函数
                    console.log(err.message);

                    //将没有权限时，跳回登录页面
                    if (err.response.status === 401) {
                        that.$message.error("请先登录")
                        that.jumpLogin()
                    }
                });
        },
        getAllStudents() {
            this.inputStr = "";
            this.getStudents();
        },
        //获取当前页的学生数据
        getPageStudents() {
            //清空pageStudents中的数据
            this.pageStudents = []
            //获得当前页的数据
            for (let i = (this.currentpage - 1) * this.pagesize; i < this.total; i++) {
                //遍历数据添加到pageStudent中
                this.pageStudents.push(this.students[i]);
                //判断是否达到一页的要求
                if (this.pageStudents.length === this.pagesize) break;
            }
        },
        //实现学生信息查询
        queryStudents() {
            //使用Ajax请求，--POST--传递inputStr
            let that = this
            //开始ajax请
            axios
                .post(
                    that.baseUrl + 'students/query/',
                    {
                        inputstr: that.inputStr
                    },
                    {
                        headers: {
                            'Authorization': 'Token ' + sessionStorage.getItem('token')
                        }
                    }
                )
                .then(
                    function (res) {
                        if (res.data.code === 1) {
                            //把数据给students
                            that.students = res.data.data;
                            //获取返回记录的总行数
                            that.total = res.data.data.length;
                            //获取当前页的数据
                            that.getPageStudents();
                            //提示
                            that.$message({
                                message: '查询数据加载成功！',
                                type: 'success'
                            });
                        } else {
                            that.$message.error(res.data.msg);
                        }
                    }
                )
                .catch(function (err) {
                    that.$message.error("获取后端查询结果出现异常");
                })

        },
        //添加学生时打开表单 
        addStudent() {
            this.dialogTitle = "新增学生信息";
            this.dialogVisible = true;
        },
        //调整当前的页页面的行数
        handleSizeChange(size) {
            // 修改当前每页的数据行数
            this.pagesize = size;
            //数据重新分页
            this.getPageStudents();

        },
        //根据ID获取image
        getImageBySno(sno) {
            //
            for (oneStudent of this.students) {
                if (oneStudent.sno == sno) {
                    return oneStudent.image;
                }
            }
        },


        //查看学生的明细
        viewStudent(row) {
            this.dialogVisible = true;
            // this.studentForm = row;
            // 深拷贝的方法01
            // this.studentForm.sno = row.sno;
            // this.studentForm.name = row.name;
            // this.studentForm.gender = row.gender;
            // this.studentForm.birthday = row.birthday;
            // this.studentForm.mobile = row.mobile;
            // this.studentForm.email = row.email;
            // this.studentForm.address = row.address;
            this.dialogTitle = "查看学生信息";
            this.isView = true;
            // 深拷贝的方法01
            this.studentForm = JSON.parse(JSON.stringify(row));
            //获取图片
            this.studentForm.image = this.getImageBySno(row.sno);
            this.studentForm.imageUrl = this.baseUrl + 'media/' + this.studentForm.image;
        },

        updateStudent(row) {
            //弹出表单
            this.dialogVisible = true;
            // 深拷贝的方法01
            this.dialogTitle = "修改学生信息";
            this.isEdit = true;
            this.studentForm = JSON.parse(JSON.stringify(row));
            this.studentForm.image = this.getImageBySno(row.sno);
            this.studentForm.imageUrl = this.baseUrl + 'media/' + this.studentForm.image;
        },
        //提交学生的表单
        submitStudentForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //校验成功后，执行添加或者修改
                    if (this.isEdit) {
                        this.submitUpdateStudent();
                    } else {
                        this.submitAddStudent();
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        //添加到数据库的函数
        submitAddStudent() {
            //定义that
            let that = this;

            axios
                .post(that.baseUrl + 'students/add/',
                    that.studentForm,
                    {
                        headers: {
                            'Authorization': 'Token ' + sessionStorage.getItem('token')
                        }
                    }
                )
                .then(res => {
                    //执行成功
                    if (res.data.code === 1) {
                        //获取所有学生的信息
                        that.students = res.data.data;
                        //获取记录条数
                        that.total = res.data.data.length;
                        //获取分页信息
                        that.getPageStudents();
                        //提示
                        that.$message({
                            message: '数据新增成功！',
                            type: 'success'
                        });
                        that.closeDialgForm('studentForm');
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err => {
                    //执行失败
                    that.console.log(str(e));
                    that.$message.error("获取后羰查询结果出现异常");
                })
        },

        //修改更新到数据库
        submitUpdateStudent(studentForm) {
            //定义that
            let that = this;

            axios
                .post(that.baseUrl + 'students/update/',
                    that.studentForm,
                    {
                        headers: {
                            'Authorization': 'Token ' + sessionStorage.getItem('token')
                        }
                    }
                )
                .then(res => {
                    //执行成功
                    if (res.data.code === 1) {
                        //获取所有学生的信息
                        that.students = res.data.data;
                        //获取记录条数
                        that.total = res.data.data.length;
                        //获取分页信息
                        that.getPageStudents();
                        //提示
                        that.$message({
                            message: '数据修改成功！',
                            type: 'success'
                        });
                        that.closeDialgForm('studentForm');
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err => {
                    //执行失败
                    that.console.log(str(e));
                    that.$message.error("修改后端查询结果出现异常");
                })
        },

        //删除一条学生记录
        deleteStudent(row) {
            this.$confirm('是否确认删除学生信息【学号：' + row.sno + '\t姓名：' + row.name + '】吗?',
                '提示', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //确认删除的响应事件
                let that = this;
                //调用后端的接口
                axios
                    .post(that.baseUrl + 'students/delete/',
                        {
                            sno: row.sno
                        },
                        {
                            headers: {
                                'Authorization': 'Token ' + sessionStorage.getItem('token')
                            }
                        }
                    )
                    .then(res => {
                        if (res.data.code === 1) {
                            //获取所有的学生信息
                            that.students = res.data.data;
                            that.total = res.data.data.length;
                            that.getPageStudents();
                        } else {
                            that.$message.error(res.data.msg);
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        //批量删除
        deleteStudents() {
            this.$confirm('是否确认删除所选择的学生吗?',
                '提示', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //确认删除的响应事件
                let that = this;
                console.log(that.selectStudents[0]['sno'])
                //调用后端的接口
                axios
                    .post(that.baseUrl + 'students/deletes/',
                        {
                            students: that.selectStudents
                        },
                        {
                            headers: {
                                'Authorization': 'Token ' + sessionStorage.getItem('token')
                            }
                        }
                    )
                    .then(res => {
                        if (res.data.code === 1) {
                            //获取所有的学生信息
                            that.students = res.data.data;
                            that.total = res.data.data.length;
                            that.getPageStudents();

                        } else {
                            that.$message.error(res.data.msg);
                        }
                    })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },


        // 关闭弹出框 的表单
        closeDialgForm(formName) {
            // 清空
            this.$refs[formName].resetFields();
            this.studentForm.sno = "";
            this.studentForm.name = "";
            this.studentForm.gender = "";
            this.studentForm.birthday = "";
            this.studentForm.mobile = "";
            this.studentForm.email = "";
            this.studentForm.address = "";
            this.studentForm.image = "";
            this.studentForm.imageUrl = "";
            //关闭弹出框
            this.dialogVisible = false;
            this.isEdit = false;
            this.isView = false;
        },


        //选择学生头像后点击确定后触发的事件
        uploadPicturePost(file) {
            //定义that
            let that = this;
            //定义一个formdata类
            let fileReq = new FormData();
            //把照片传进去
            fileReq.append('avatar', file.file);
            //使用axios发起ajax请求
            axios(
                {
                    headers: {
                        'Authorization': 'Token ' + sessionStorage.getItem('token')
                    },
                    method: 'post',
                    url: that.baseUrl + 'pic/upload/',
                    data: fileReq
                }
            )
                .then(res => {
                    //根据code判断是否成功
                    if (res.data.code === 1) {
                        //把照片给image
                        that.studentForm.image = res.data.name;
                        //拼接imageUrl
                        that.studentForm.imageUrl = that.baseUrl + 'media/' + res.data.name;
                    } else {
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err => {
                    console.log(err);
                    that.$message.error('上传图像出现异常');
                })
        },

        //导入Excel
        inputExcel(file) {

            let that = this;
            let fileReq = new FormData();
            fileReq.append('Excel', file.file);

            axios(
                {   
                    headers: {
                        'Authorization': 'Token ' + sessionStorage.getItem('token')
                    },
                    method: 'post',
                    url: that.baseUrl + 'students/inputstudent/',
                    data: fileReq
                }
            )
                .then(res => {
                    //获取所有的学生信息
                    that.students = res.data.data;
                    that.total = res.data.data.length;
                    that.getPageStudents();
                    that.$message({
                        message: res.data.msg,
                        type: 'success'
                    })
                    console.log(res.data.sno)
                })
                .catch(err => {
                    console.log(err);
                    that.$message.error('导入学生数据异常以');
                })
        },


        //导出学生信息
        exprtExcel() {
            let that = this;
        },

        //调整当前的页码
        handleCurrentChange(pageNuber) {
            //修改当前的页码
            this.currentpage = pageNuber;
            //数据重新分页产
            this.getPageStudents();
        },

        //选择复选择框执行的操作
        handleSelectionChange(data) {
            this.selectStudents = data;
            //console.log(data);
        },

        logout(){
            sessionStorage.removeItem("token")

            this.$message({
                type: 'success',
                message: '退出成功',
            });
            
            setTimeout(this.jumpLogin(),6000)
            
            
        },

        jumpLogin() {
            window.location.href = "../../login.html"
        }
    },
})